import { resolveImportMap, resolveIfNotPlainOrUrl, BASE_URL } from "../common";
import { SystemJSCore } from "../system-core";
import { errMsg } from "../err-msg";

export const resolve = function (
    this: SystemJSCore,
    id: string,
    parentUrl = this[BASE_URL]
) {
    return (
        resolveImportMap(
            this.importMap,
            resolveIfNotPlainOrUrl(id, parentUrl) || id,
            parentUrl
        ) || throwUnresolved(id, parentUrl)
    );
};

function throwUnresolved(id: string, parentUrl?: string) {
    throw Error(
        errMsg(
            8,
            process.env.SYSTEM_PRODUCTION
                ? [id, parentUrl].join(", ")
                : "Unable to resolve bare specifier '" +
                      id +
                      (parentUrl ? "' from " + parentUrl : "'")
        )
    );
}
